import json

from django.contrib.auth import login, authenticate, logout
from django.http import JsonResponse, HttpResponse
from django.shortcuts import render
from django_redis import get_redis_connection
# Create your views here.
from django.views import View
import re
from apps.users.models import *
from apps.users.untils import generate_verify_email_url, check_verify_email_token
from celery_tasks.email.tasks import send_email_code
from untils.views import LoginRequiredJSONMixin


class UsernameCountView(View):

    def get(self, request, username):
        print(username)
        try:
            count = User.objects.filter(username=username).count()
        except Exception as e:
            return JsonResponse({"code": 15, "errmsg": "数据异常"})

        print("count=", count)
        return JsonResponse({"count": count, "code": 1, "errmsg": "OK"})


class MobileCountView(View):

    def get(self, request, mobile):
        print(mobile)
        try:
            count = User.objects.filter(mobile=mobile).count()
        except Exception as e:
            print(e)
            return JsonResponse({"code": 16, "errmsg": "数据异常"})
        print('count mobile', count)
        return JsonResponse({"count": count, "code": 1, "errmsg": "OK"})


class RegisterView(View):

    def post(self, request):
        dict = request.body
        data_dict = json.loads(dict)
        username = data_dict.get('username')
        password = data_dict.get('password')
        password2 = data_dict.get('password2')
        mobile = data_dict.get('mobile')
        sms_code = data_dict.get('sms_code')
        allow = data_dict.get('allow')

        redis = get_redis_connection('code')

        # sms_code_redis = redis.get('sms_code%s' % mobile)
        # if not sms_code_redis:
        #     return JsonResponse({'code': 400, 'errmsg': '短信验证码失效'})
        try:
            sms_code_redis = redis.get('sms_code%s' % mobile)
        except Exception:
            return JsonResponse({'code': 400, 'errmsg': '短信验证码失效'})
        sms_code_redis = sms_code_redis.decode()
        if sms_code != sms_code_redis:
            return JsonResponse({'code': 400, 'errmsg': '短信验证码有误'})

        # print(username, password2, password, mobile, sms_code, allow)
        if not all([username, password, password2, mobile, sms_code, allow]):
            return JsonResponse({'code': 400, 'errmsg': '数据上传错误'})
        try:
            user = User.objects.create_user(username=username, password=password, mobile=mobile)
        except Exception as e:
            print(e)
            return JsonResponse({'code': 400, 'errmsg': '注册失败1'})
        login(request, user)
        response = JsonResponse({'code': 0, 'errmsg': '注册成功'})
        response.set_cookie('username', user.username, max_age=3600 * 24 * 15)
        return response


class LoginView(View):
    def post(self, request):
        # 1 接收json数据
        body = request.body
        data_dict = json.loads(body)
        username = data_dict.get('username')
        password = data_dict.get('password')
        remembered = data_dict.get('remembered')

        # 2 验证数据是否为空  正则
        if not all([username, password, remembered]):
            return JsonResponse({'code': 400, 'errmsg': '写错了'})
        # 3 验证码用户名和密码是否正确
        if re.match('^1[3-9]\d{9}$', username):
            # 手机号
            User.USERNAME_FIELD = 'mobile'
        else:
            # account 是用户名
            # 根据用户名从数据库获取 user 对象返回.
            User.USERNAME_FIELD = 'username'
        user = authenticate(username=username, password=password)
        print(user,'LoginUser')
        if not user:
            return JsonResponse({'code': 400, 'errmsg': '用户名密码错误'})

        # 4 状态保持
        login(request, user)

        # 5 判断是否记住登录
        if remembered:
            # 如果记住:  设置为两周有效
            request.session.set_expiry(None)
        else:
            # 如果没有记住: 关闭立刻失效
            request.session.set_expiry(0)
        # 6 返回响应
        response = JsonResponse({'code': 0, 'errmsg': 'ok'})
        response.set_cookie('username', user.username, max_age=3600 * 24 * 15)
        return response


class LogoutView(View):

    def delete(self, request):
        """实现退出登录逻辑"""
        # 清理session
        logout(request)
        # 退出登录，重定向到登录页
        response = JsonResponse({'code': 0,
                                 'errmsg': 'ok'})
        # 退出登录时清除cookie中的username
        response.delete_cookie('username')

        return response


class UserInfoView(LoginRequiredJSONMixin, View):
    def get(self, request):
        return JsonResponse({
            "code": 0,
            "errormsg": "ok",
            "info_data": {
                "username": request.user.username,
                "mobile": request.user.mobile,
                "email": request.user.email,
                "email_active": request.user.email_active
            }

        })


class SaveEmasilView(View):
    def put(self, request):
        body = request.body
        data_dict = json.loads(body)
        email = data_dict.get('email')
        if not email: return JsonResponse({'code': 100, 'errmsg': '未登录'})
        try:
            request.user.email = email
            request.user.save()
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': '数据库未找到'})
        verify_url = generate_verify_email_url(request.user)
        messgae_html = '<p><a href="%s">点击激活</a></p>' % (verify_url)
        send_email_code.delay(email, messgae_html)

        return JsonResponse({'code': 0, 'errmsg': 'ok'})


class EmailsVerify(View):
    def put(self, request):

        # - 1 接收请求（PUT）数据
        # - 2 获取token
        token = request.GET.get('token')
        # - 3 对token解密 获取解密数据里的user_id
        user_id = check_verify_email_token(token)
        print(user_id,'user_id数据')
        # - 5 如果获取不到 说明过期
        if not user_id:
            return JsonResponse({'code': 400, 'errmsg': '激活邮件已经过期'})
        # - 6 根据user_id去数据库查询
        try:
            user = User.objects.get(username=user_id)
            print(user)
        except Exception as e:
            print(e)
            return JsonResponse({'code': 405, 'errmsg': '当前用户不存在'})
        # - 7 把查到user对象的 email_active字段 改为true 不要忘记save
        user.email_active = True
        user.save()
        return JsonResponse({'code': 0, 'errmsg': '激活成功'})
